<?php

namespace app\tool\controller;

use think\Controller;
use think\facade\Validate;

class Tool extends Controller
{
    /**
     * @title 短信发送
     * @param integer $type 1是不验证手机；2是验证手机
     * @param string $phone 手机号
     *
     * @return code:1发送成功，不是1则是发送失败
     * @return msg:短信发送信息
     */
    public function sendSms($type, $phone)
    {
        if ($type == 1) {
            $rules = [
                'phone|手机号' => 'require|mobile'
            ];
        } elseif ($type == 2) {
            $rules = [
                'phone|手机号' => 'require|mobile|unique:user'
            ];
        } else {
            $rules = [];
        }
        $validate = Validate::make($rules);
        if (!$validate->check(['phone' => $phone])) {
            return ['code' => 0, 'msg' => $validate->getError()];
        } else {
            $code = rand(1000, 9999);
            cache('code' . $phone, $code, config('extra.sms.expire'));
            if (config('extra.sms.debug')) {
                return ['code' => 1, 'msg' => '发送成功！验证码是：' . $code];
            } else {
                // 集成短信扩展
                return ['code' => 1, 'msg' => '发送成功！'];
            }
        }
    }

    /**
     * @title 压缩文件
     * @param file $file 文件
     * @param string $path 文件路径
     * @param integer $compress 1压缩，0不压缩
     *
     * @return string 文件路径
     */
    public function fileCompress($file, $path = 'avatar', $compress = 1)
    {
        $savePath = env('root_path') . '/public/uploads/' . $path . '/';
        if (!is_dir($savePath)) {
            mkdir($savePath, 0777, true);
        }
        if ($compress == 0) {
            $info = $file->move($savePath);
            $url = '/uploads/' . $path . '/' . $info->getSaveName();
            $url = str_replace('\\', '/', $url);
            return $url;
        }
        $saveName = uniqid() . '.jpg';
        $bool = $file->checkSize(config('extra.file_size'));
        $image = \think\Image::open($file);
        if ($bool) {
            $image->save($savePath . $saveName, 'png', 100, true);
        } else {
            $image->save($savePath . $saveName, 'jpg', 10, true);
        }
        $url = '/uploads/' . $path . '/' . $saveName;
        return trim($url, '.');
    }
}
